package com.github.binarywang.demo.wx.mp.controller;

import java.util.*;
import java.util.Map.Entry;

import cc.openkit.common.KitUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/mydb")
public class TestController {


    @Autowired
    private JdbcTemplate jdbcTemplate;

    @RequestMapping("/getUsers")
    public List<Map<String, Object>> getDbType(){
        String sql = "select * from appuser";
        List<Map<String, Object>> list =  jdbcTemplate.queryForList(sql);
        for (Map<String, Object> map : list) {
            Set<Entry<String, Object>> entries = map.entrySet( );
            if(entries != null) {
                Iterator<Entry<String, Object>> iterator = entries.iterator( );
                while(iterator.hasNext( )) {
                    Entry<String, Object> entry =(Entry<String, Object>) iterator.next( );
                    Object key = entry.getKey( );
                    Object value = entry.getValue();
                    System.out.println(key+":"+value);
                }
            }
        }
        return list;
    }

//    /**
//     * 添加
//     * @param name
//     * @param openid
//     * @param phone
//     * @return
//     */
//    @RequestMapping("/add/{name}/{phone}/{openid}")
//    public Object add(@PathVariable String name,@PathVariable String openid,@PathVariable String phone){
//
//        String sql = "insert INTO appuser(id,username,openid,user_phone,user_time) VALUES (?,?,?,?,?)";
//        System.out.println(sql);
//
//        Object args[] = {KitUtil.uuid(),name,openid,phone,new Date()};
//        int temp = jdbcTemplate.update(sql, args);
//        Map<String, Object> map = new HashMap<String, Object>();
//
//        if (temp > 0) {
//            System.out.println("插入成功！");
//            map.put("code",2000);
//        }else{
//            System.out.println("插入失败");
//            map.put("code",1000);
//            map.put("msg","绑定失败");
//        }
//        return JSONObject.toJSON(map);
//    }


    @RequestMapping("/user/{id}")
    public Map<String,Object> getUser(@PathVariable String id){
        Map<String,Object> map = null;
        List<Map<String, Object>> list = getDbType();
        for (Map<String, Object> dbmap : list) {

            Set<String> set = dbmap.keySet();

            for (String key : set) {
                if(key.equals("id")){
                    if(dbmap.get(key).equals(id)){
                        map = dbmap;
                    }
                }
            }
        }

        if(map==null){
            map = list.get(0);
        }

        return map;
    }


}
